/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function frac(f) {
    return Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))));
}
function calculatepayment() {
    var loan_amount = document.getElementById('CustomerLoanSetting_loan_amount');
    var installments = document.getElementById('CustomerLoanSetting_installments');
    var paying_amount = document.getElementById('CustomerLoanSetting_paying_amount');
    var payment_per_installment = document.getElementById('CustomerLoanSetting_payment_per_installment');
    var last_period_payment = document.getElementById('CustomerLoanSetting_last_period_payment');
    var interest = document.getElementById('CustomerLoanSetting_interest');
    
    if (installments.value == 0) {
        installments.value = 1;
    }  // avoid divide by zero

    var pay1 = paying_amount.value / installments.value;
    if (frac(pay1) > 0) {
        paymentperinstallment = Math.ceil(pay1);
        lastperiodpayment = paying_amount.value - (paymentperinstallment * (installments.value - 1));
    } else {
        paymentperinstallment = pay1;
        lastperiodpayment = pay1;
    }

    interest.value = sprintf('%d', (paying_amount.value - loan_amount.value) / loan_amount.value * 100);
    payment_per_installment.value = sprintf('%.2f', paymentperinstallment);
    last_period_payment.value = sprintf('%.2f', lastperiodpayment);
}

